package com.huluobo.day11_im;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;
import com.huluobo.day11_im.activity.ChatActivity;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseIM;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.util.List;

public class IMApp extends Application {
    public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{2,19}$";
    public static final String REGEX_PASSWORD = "^[0-9]{3,20}$";

    public static final String CHAT_CONVERSATION_ID = "conversationId";

    public static final String CHAT_TYPE = "chatType";

    public static final int CHAT_TYPE_SINGLE = 1;

    public static final int CHAT_TYPE_GROUP = 2;

    private EMMessageListener emMessageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            if (!isForeground()) {
                //声音,左声道,右声道,优先级,循环次数,播放速度
                soundPool.play(yulu, 1f, 1f, 0, 0, 1f);
                showNotification(messages);
            } else {
                soundPool.play(duan, 1f, 1f, 0, 0, 1f);
            }
        }
    };

    //是一个声音池,类似线程池,需要给他设置最大线程数,这里设置为10
    private SoundPool soundPool = new SoundPool.Builder().setMaxStreams(10).build();

    //处于前台的音乐
    private int duan;

    //处于后台的音乐
    private int yulu;

    private void showNotification(List<EMMessage> messages) {
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        for (int i = 0; i < messages.size(); i++) {
            String contentText = "文本";
            if (messages.get(i).getType() == EMMessage.Type.TXT) {
                contentText = ((EMTextMessageBody) messages.get(i).getBody()).getMessage();
            } else if (messages.get(i).getType() == EMMessage.Type.FILE) {
                contentText = "[文件]";
            } else if (messages.get(i).getType() == EMMessage.Type.IMAGE) {
                contentText = "[图片]";
            }

            Intent intent = new Intent(this, ChatActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(CHAT_CONVERSATION_ID, messages.get(i).conversationId());

            if (messages.get(i).getChatType() == EMMessage.ChatType.Chat) {
                bundle.putInt(CHAT_TYPE, CHAT_TYPE_SINGLE);
            } else {
                bundle.putInt(CHAT_TYPE, CHAT_TYPE_GROUP);
            }
            intent.putExtras(bundle);
            //taskStackBuilder 会先打开ChatActivity的父activity,再打开ChatActivity
            TaskStackBuilder taskStackBuilder =
                    TaskStackBuilder.create(this).addParentStack(ChatActivity.class).addNextIntent(intent);
            PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);

//            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
//                    PendingIntent.FLAG_UPDATE_CURRENT);
            Notification notification = new Notification.Builder(this)
                    .setContentTitle("收到新消息")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                            R.mipmap.ic_launcher))
                    .setContentIntent(pendingIntent)
                    .setContentText(contentText)
                    .setAutoCancel(true)
                    .build();

            notificationManager.notify(1, notification);
        }
    }

    //判断当前应用程序是否处于前台位置
    private boolean isForeground() {
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo :
                activityManager.getRunningAppProcesses()) {
            //找到当前运行app的进程优先级
            //判断当前app运行的优先级是否等于前台的优先级
            return runningAppProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
        }
        return false;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //环信初始化
        EMOptions emOptions = new EMOptions();
        emOptions.setAppKey("moroks#day11im2103a");
//        EMClient.getInstance().init(this, emOptions);

        //EaseIM 初始化
        if (EaseIM.getInstance().init(this, emOptions)) {
            //在做打包混淆时，关闭 debug 模式，避免消耗不必要的资源
            EMClient.getInstance().setDebugMode(true);
            //EaseIM 初始化成功之后再调用注册消息监听的代码 ...
        }

        //二维码初始化
        ZXingLibrary.initDisplayOpinion(this);
//        EMClient.getInstance().chatManager().addMessageListener(emMessageListener);
        duan = soundPool.load(this, R.raw.duan, 0);
        yulu = soundPool.load(this, R.raw.yulu, 0);
    }
}
